package com.rshang.rsdp.service.impl;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import com.rshang.rsdp.annotation.Log;
import com.rshang.rsdp.bean.DataGrid;
import com.rshang.rsdp.bean.Response;
import com.rshang.rsdp.common.status.DicStatusCode;
import com.rshang.rsdp.common.status.ExcelStatusCode;
import com.rshang.rsdp.common.status.StatusCode;
import com.rshang.rsdp.entity.DmRsdlGsa;
import com.rshang.rsdp.entity.TbDictory;
import com.rshang.rsdp.exception.RsdpSystemException;
import com.rshang.rsdp.kit.StrKits;
import com.rshang.rsdp.mapper.TbDictoryMapper;
import com.rshang.rsdp.service.IExcelService;
import com.rshang.rsdp.service.ITbDictoryService;
import com.rshang.rsdp.util.excel.CellKey;
import com.rshang.rsdp.util.i18n.I18nMessage;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * <p>
 * 数据字典信息表 服务实现类
 * </p>
 *
 * @author zhangjun
 * @since 2017-08-11
 */
@Service
public class TbDictoryServiceImpl extends ServiceImpl<TbDictoryMapper, TbDictory> implements ITbDictoryService {

    private static final Logger logger = LoggerFactory.getLogger(TbDictoryServiceImpl.class);

    @Autowired
    I18nMessage i18n;

    @Autowired
    IExcelService excel;

    private static final List<CellKey> COLUMN_IMPORT = new ArrayList<CellKey>() {{
        add(new CellKey("分类", "1", 100, true));//1字符型 2数字型 3日期型 4日期时间 9其他
        add(new CellKey("代码", "1", 20, true));
        add(new CellKey("名称", "1", 100, true));
        add(new CellKey("简称", "1", 50, false));
    }};

    @Override
    public DataGrid getDicPageList(Page<HashMap> page, HttpServletRequest request) {
        String dmfl = StrKits.emptyToStr(request.getParameter("dmfl"));
        String xm = StrKits.emptyToStr(request.getParameter("dm"));
        String mc = StrKits.emptyToStr(request.getParameter("mc"));

        page.setRecords(this.baseMapper.getDicPageList(page, dmfl, xm, mc));
        return new DataGrid(page.getRecords(), page.getTotal());
    }

    @Override
    public List<TbDictory> getDmFl() {
        return this.baseMapper.selectList(Condition.create()
                .setSqlSelect(" distinct DIC_FL,DIC_FL")
                .orderBy("DIC_FL"));
    }

    @Override
    public Response checkDmfl(HttpServletRequest request) {
        String id = StrKits.emptyToStr(request.getParameter("id"));
        Wrapper wrapper = Condition.create().setSqlSelect("DIC_ID")
                .eq("DIC_FL", StrKits.emptyToStr(request.getParameter("fl")))
                .eq("DIC_DM", StrKits.emptyToStr(request.getParameter("dm")));
        //.eq("DIC_MC", StrKits.emptyToStr(request.getParameter("mc")))
        if (!"".equals(id)) {
            wrapper = wrapper.ne("DIC_ID", id);
        }

        if (this.baseMapper.selectCount(wrapper) > 0) {
            throw new RsdpSystemException(DicStatusCode.DIC_FOUND.getCode(), i18n.getMessage(DicStatusCode.DIC_FOUND.getKey()));
        }
        return new Response(StatusCode.SUCCESS.getCode(), i18n.getMessage(StatusCode.SUCCESS.getKey()));
    }

    @Log(module = "数据字典", desc = "新增字典")
    @Override
    public Response addSave(HttpServletRequest request, String czr) {
        TbDictory dic = new TbDictory();
        dic.setDicFl(StrKits.emptyToStr(request.getParameter("dicfl")));
        dic.setDicDm(StrKits.emptyToStr(request.getParameter("dicdm")));
        dic.setDicMc(StrKits.emptyToStr(request.getParameter("dicqc")));
        TbDictory result = this.baseMapper.selectOne(dic);
        if (result != null) {
            throw new RsdpSystemException(DicStatusCode.DIC_FOUND.getCode(), i18n.getMessage(DicStatusCode.DIC_NOTFOUND.getKey()));
        } else {
            dic.setDicId(StrKits.uuid());
            dic.setDicJc(StrKits.emptyToStr(request.getParameter("dicjc")));
            dic.setLrr(czr);
            dic.setXgr(czr);
            dic.setYxBz(StrKits.emptyToStr(request.getParameter("sel_yxbz")));
            dic.setXyBz(StrKits.emptyToStr(request.getParameter("sel_xybz")));
            if (this.baseMapper.insert(dic) > 0) {
                return new Response(StatusCode.SUCCESS.getCode(), i18n.getMessage(StatusCode.SUCCESS.getKey()));
            } else {
                return new Response(StatusCode.OPER_FAILED.getCode(), i18n.getMessage(StatusCode.OPER_FAILED.getKey()));
            }
        }
    }

    @Log(module = "数据字典", desc = "字典编辑")
    @Override
    public Response editSave(HttpServletRequest request, String czr) {
        TbDictory result = this.baseMapper.selectById(StrKits.emptyToStr(request.getParameter("hid_id")));
        if (result == null) {
            throw new RsdpSystemException(DicStatusCode.DIC_FOUND.getCode(), i18n.getMessage(DicStatusCode.DIC_NOTFOUND.getKey()));
        } else {
            result.setDicDm(StrKits.emptyToStr(request.getParameter("dicdm")));
            result.setDicId(StrKits.emptyToStr(request.getParameter("hid_id")));
            result.setDicJc(StrKits.emptyToStr(request.getParameter("dicjc")));
            result.setXgr(czr);
            result.setXgsj(new Date());
            result.setYxBz(StrKits.emptyToStr(request.getParameter("sel_yxbz")));
            result.setXyBz(StrKits.emptyToStr(request.getParameter("sel_xybz")));
            if (this.baseMapper.updateAllColumnById(result) > 0) {
                return new Response(StatusCode.SUCCESS.getCode(), i18n.getMessage(StatusCode.SUCCESS.getKey()));
            } else {
                return new Response(StatusCode.OPER_FAILED.getCode(), i18n.getMessage(StatusCode.OPER_FAILED.getKey()));
            }
        }
    }

    @Log(module = "数据字典", desc = "字典删除")
    @Override
    public Response deleteSave(HttpServletRequest request, String czr) {
        TbDictory result = this.baseMapper.selectById(StrKits.emptyToStr(request.getParameter("id")));
        if (result == null)//数据字典不存在
        {
            throw new RsdpSystemException(DicStatusCode.DIC_NOTFOUND.getCode(), i18n.getMessage(DicStatusCode.DIC_NOTFOUND.getKey()));
        } else        //物理删除
        {
            if (this.baseMapper.deleteById(result) > 0) {
                return new Response(StatusCode.SUCCESS.getCode(), i18n.getMessage(StatusCode.SUCCESS.getKey()));
            } else {
                return new Response(StatusCode.OPER_FAILED.getCode(), i18n.getMessage(StatusCode.OPER_FAILED.getKey()));
            }

        }
    }

    @Override
    public TbDictory get(HttpServletRequest request) {
        TbDictory result = this.selectById(StrKits.emptyToStr(request.getParameter("id")));
        if (result == null) {
            throw new RsdpSystemException(DicStatusCode.DIC_NOTFOUND.getCode(), i18n.getMessage(DicStatusCode.DIC_NOTFOUND.getKey()));
        } else {
            return result;
        }
    }

    @Override
    public List<TbDictory> getDicByFl(String dicFl) {
        return this.baseMapper.selectList(Condition.create().eq("DIC_FL", StrKits.emptyToStr(dicFl)).eq("YX_BZ", "1").eq("XY_BZ", "1").orderBy("DIC_DM"));
    }

    @Override
    public List<HashMap> getDicListByFl(String fl) {
        return this.baseMapper.getDicListByFl(fl);
    }

    @Override
    @Transactional
    @Log(module = "数据字典", desc = "模板导入")
    public Response importSave(MultipartFile file, String czr) {
        if (file == null)//文件为空
        {
            throw new RsdpSystemException(ExcelStatusCode.XLS_EMPTY.getCode(), i18n.getMessage(ExcelStatusCode.XLS_EMPTY.getKey()));
        }
        InputStream is = null;
        Workbook wb = null;
        Sheet sheet = null;
        Row row = null;
        Cell cell0 = null;
        Cell cell1 = null;
        Cell cell2 = null;
        Cell cell3 = null;
        List<Row> data = new ArrayList<Row>();
        List<String> errList = new ArrayList<String>();
        try {
            is = file.getInputStream();
            wb = new HSSFWorkbook(is);

            if (wb.getNumberOfSheets() == 0)//模板必须要有一个sheet表
            {
                throw new RsdpSystemException(ExcelStatusCode.XLS_NOTFORMATED.getCode(), i18n.getMessage(ExcelStatusCode.XLS_NOTFORMATED.getKey()));
            }
            //读取excel文件
            sheet = wb.getSheetAt(0);//读取第一个sheet表
            int rowCount = sheet.getPhysicalNumberOfRows();//获取模板总数
            logger.debug("dic importSave row count:{}", rowCount);
            if (rowCount < 2)//空数据
            {
                throw new RsdpSystemException(ExcelStatusCode.XLS_DATAEMPTY.getCode(), i18n.getMessage(ExcelStatusCode.XLS_DATAEMPTY.getKey()));
            }
            //循环读取数据
            Iterator<Row> it = sheet.iterator();
            int rowNo = 0;
            CellKey cellKey;
            //循环读取数据
            while (it.hasNext()) {
                row = it.next();
                if (row != null && row.getRowNum() > 0) {
                    rowNo = row.getRowNum();
                    //logger.debug("xgs importSave row:{}-{}-{}",cell0,cell1,cell2);
                    //模板校验
                    for (int i = 0; i < 4; i++) {
                        excel.setStringCell(row.getCell(i));
                        cellKey = COLUMN_IMPORT.get(i);
                        excel.checkCellValue(rowNo, i, cellKey, row.getCell(i), errList);
                    }

                    if (errList.size() > 0) {
                        if (!data.isEmpty()) {
                            data.clear();
                        }
                    } else {
                        data.add(row);
                    }
                }
            }

        } catch (IOException e) {
            logger.error("dic importSave error:{}", e.getMessage());
            throw new RsdpSystemException(StatusCode.SERVER_ERROR.getCode(), e.getMessage());
        } finally {
            try {
                //关闭流及文件
                wb.close();
                is.close();
            } catch (IOException e) {
                logger.error("dic importSave close error:{}", e.getMessage());
            }
        }
        if (errList.size() > 0)//模板校验错误直接抛出
        {
            return new Response(ExcelStatusCode.XLS_ERROR.getCode(), i18n.getMessage(ExcelStatusCode.XLS_ERROR.getKey(), new Object[]{Joiner.on("").join(errList)}));
        } else {
            String plId = StrKits.uuid();
            Map dicMap = new HashMap();
            List<TbDictory> dicList = this.baseMapper.selectList(Condition.create());
            for (TbDictory dic : dicList) {
                dicMap.put(dic.getDicFl() + "-" + dic.getDicDm() + "-" + dic.getDicMc() + "-" + dic.getDicJc(), dic.getDicId());
            }
            for (Row rt : data) {
                cell0 = rt.getCell(0);//分类
                cell1 = rt.getCell(1);//代码
                cell2 = rt.getCell(2);//名称
                cell3 = rt.getCell(3);//简称
                if (!dicMap.containsKey(cell0.getStringCellValue() + "-" + cell1.getStringCellValue() + "-" + cell2.getStringCellValue() + "-" + ((cell3 == null || StringUtils.isEmpty(cell3.getStringCellValue())) ? cell2.getStringCellValue() : cell3.getStringCellValue()))) {
                    TbDictory dic = new TbDictory();
                    dic.setDicFl(cell0.getStringCellValue());
                    dic.setDicDm(cell1.getStringCellValue());
                    dic.setDicMc(cell2.getStringCellValue());
                    dic.setDicId(StrKits.uuid());
                    dic.setDicJc((cell3 == null || StringUtils.isEmpty(cell3.getStringCellValue())) ? cell2.getStringCellValue() : cell3.getStringCellValue());
                    dic.setLrr(czr);
                    dic.setXgr(czr);
                    dic.setYxBz("1");
                    dic.setXyBz("1");
                    if (this.baseMapper.insert(dic) < 0) {
                        return new Response(StatusCode.OPER_FAILED.getCode(), i18n.getMessage(StatusCode.OPER_FAILED.getKey()));
                    }
                    dicMap.put(dic.getDicFl() + "-" + dic.getDicDm() + "-" + dic.getDicMc() + "-" + dic.getDicJc(), dic.getDicId());
                }

            }
        }
        return new Response(StatusCode.SUCCESS.getCode(), i18n.getMessage(StatusCode.SUCCESS.getKey()));
    }

}
